<template>
	<el-dialog :title="dialog.title" v-model="dialog.isShowDialog" width="500px">
		<el-form ref="formRef" :model="ruleForm" :rules="rules" label-width="78px">
			<el-row class="mb20">
				<el-col :span="24">
					<el-form-item label="角色名称" prop="role_name">
						<el-input v-model="ruleForm.role_name" placeholder="请输入角色名称" clearable />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row class="mb20">
				<el-col :span="24">
					<el-form-item label="角色排序" prop="display_order">
						<el-input v-model="ruleForm.display_order" placeholder="请输入角色排序" clearable @input="onVerifiyDisplayOrderNumberInteger" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="24">
					<el-form-item label="菜单权限">
						<el-tree
							ref="treeMenuRef"
							:data="menuData"
							empty-text="加载中，请稍候"
							node-key="id"
							:props="menuProps"
							show-checkbox
							class="menu-data-tree"
						/>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<el-button @click="onCancel" size="small">取 消</el-button>
			<el-button type="primary" @click="onSubmit" :loading="dialog.submitLoading" size="small">提 交</el-button>
		</template>
	</el-dialog>
</template>

<script lang="ts">
import { nextTick, reactive, ref, toRefs } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { roleApi } from '/@/api/admin/index';
import admin from '/@/mock/adminMenu1.json';
import { verifiyNumberInteger } from '/@/utils/toolsValidate';
import { generateTree } from '/@/utils/utils';

const RoleApi = roleApi();
export default {
	setup() {
		const { t } = useI18n();
		let callback: Function = () => {};
		const state = reactive({
			dialog: {
				isShowDialog: false,
				type: '',
				title: '',
				submitLoading: false,
			},
			ruleForm: {
				role_name: '',
				display_order: '',
				menu: '',
				id: '',
			},
			rules: {
				role_name: [{ required: true, message: '角色名称不能为空', trigger: ['blur'] }],
				display_order: [{ required: true, message: '角色排序不能为空', trigger: ['blur'] }],
			},
			menuProps: {
				children: 'children',
				label: 'label',
			},
			menuData: [] as any,
		});
		const formRef = ref();
		const treeMenuRef = ref();

		/********** 点击事件 **********/
		// 排序正整数
		const onVerifiyDisplayOrderNumberInteger = (val: string) => {
			state.ruleForm.display_order = verifiyNumberInteger(val);
		};
		// 取消
		const onCancel = () => {
			state.dialog = {
				isShowDialog: false,
				type: '',
				title: '',
				submitLoading: false,
			};
		};
		// 提交
		const onSubmit = () => {
			(formRef.value as any)?.validate((valid: boolean) => {
				if (!valid) return;
				// const SetConstructorMenu = new Set(getMenuAllCheckedKeys());
				// const relevanceMenuTree = headOfficeMenuJson.filter((x: any) => SetConstructorMenu.has(x.id));
				// const menuTree = generateTree(relevanceMenuTree, 0, { idName: 'id', pidName: 'pid', childrenName: 'children' });
				state.ruleForm.menu = JSON.stringify(getMenuAllCheckedKeys());
				state.dialog.submitLoading = true;
				if (state.dialog.type === 'add') {
					_roleAdd(state.ruleForm);
				} else {
					_roleEdit({
						...state.ruleForm,
						role_id: state.ruleForm.id,
					});
				}
			});
		};

		/********** 方法事件 **********/
		// 打开弹窗
		const openDialog = (data: any, params: any, fn: Function) => {
			state.dialog = {
				isShowDialog: true,
				type: data.type,
				title: data.title,
				submitLoading: false,
			};
			callback = fn;
			const menuJson = admin.map((item: any) => {
				return {
					id: item.id,
					pid: item.pid,
					disabled: [1,64,65].includes(item.id),
					label: t(item.meta.title),
				};
			});
			state.menuData = generateTree(menuJson, 0, { idName: 'id', pidName: 'pid', childrenName: 'children' });
			nextTick(() => {
				(formRef.value as any)?.resetFields();
				if (data.type === 'edit') {
					JSON.parse(params.menu).map((item: any) => {
						(treeMenuRef.value as any)?.setChecked(item, true, false);
					});
					state.ruleForm = { ...params };
				} else {
					[1].map((item) => {
						(treeMenuRef.value as any)?.setChecked(item, true, false);
					});
				}
			});
		};
		// 所有菜单节点数据
		const getMenuAllCheckedKeys = () => {
			// 目前被选中的菜单节点
			let checkedKeys = (treeMenuRef.value as any)?.getCheckedKeys();
			// 半选中的菜单节点
			let halfCheckedKeys = (treeMenuRef.value as any)?.getHalfCheckedKeys();
			checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
			return checkedKeys;
		};

		/********** 网络事件 **********/
		// 添加角色
		const _roleAdd = (params: object) => {
			RoleApi.roleAdd(params)
				.then(() => {
					ElMessage.success('操作成功！');
					onCancel();
					callback();
				})
				.catch(() => (state.dialog.submitLoading = false));
		};
		// 编辑角色
		const _roleEdit = (params: object) => {
			RoleApi.roleEdit(params)
				.then(() => {
					ElMessage.success('操作成功！');
					onCancel();
					callback();
				})
				.catch(() => (state.dialog.submitLoading = false));
		};

		return {
			formRef,
			treeMenuRef,
			onVerifiyDisplayOrderNumberInteger,
			onCancel,
			onSubmit,
			openDialog,
			...toRefs(state),
		};
	},
};
</script>

<style scoped lang="scss">
.menu-data-tree {
	width: 100%;
	border: 1px solid #dcdfe6;
	border-radius: 5px;
	padding: 5px;
}
</style>
